<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>计算属性</title>
  </head>
  <body>
    <div id="app">
      <!-- 1、计算属性的使用 -->
      <h1>{{ fullName }}</h1>

      <!-- 2、计算总价格 -->
      <h2>总价格：{{ totalPrice }}</h2>

      <!-- 3、计算属性完整写法 -->
      <div class="com-full">
        <h3>{{ fullName2 }}</h3>
        <button @click="changeVal">改变计算属性的值</button>
      </div>
    </div>

    <script src="./lib/vue_v2.6.14.js"></script>
    <script>
      const app = new Vue({
        el: '#app',
        computed: {
          // 完成名字
          fullName() {
            return this.firstName + '----' + this.lastName;
          },

          // 总价格
          totalPrice() {
            let total = 0;
            this.books.map(item => {
              total += item.price;
            });
            return total;
          },

          // 计算属性完整写法
          fullName2: {
            get() {
              return `${this.firstName2} - ${this.lastName2}`;
            },
            set(val) {
              const names = val.split(' ');
              this.firstName2 = names[0];
              this.lastName2 = names[1];
            }
          }
        },
        data: {
          firstName: '张三',
          lastName: '李四',
          books: [
            { id: 1, name: 'Unix编程艺术', price: 110 },
            { id: 2, name: '代码大全', price: 98 },
            { id: 3, name: '深入理解计算机原理', price: 90 },
            { id: 4, name: '现代操作系统', price: 88 }
          ],

          firstName2: '王五',
          lastName2: '赵六'
        },
        methods: {
          // 改变计算属性的值
          changeVal() {
            this.fullName2 = '刘备 关羽';
          }
        }
      });
    </script>
  </body>
</html>
